import subprocess as sub
import shlex,math
def getLength(p1,p2):
	#print "points: ",p1,p2
	dx = int(p2[1]) - int(p1[1])
	#print "strange: " ,p1[2]
	dy = int(p2[2]) - int(p1[2])
	return int(math.sqrt(math.pow(dx,2) + math.pow(dy,2) ))
	
def getUTM(a):
	a = shlex.split("%.6f %.6f"%(a[0]/1000000.0,a[1]/1000000.0))
	p = sub.Popen(("./GeoConvert",a[0],a[1]),stdout=sub.PIPE,stderr=sub.PIPE)
	output, errors = p.communicate()
	return shlex.split(output)
def rotatePoint(p,angle):
	return (int(p[1])*math.cos(angle)-int(p[2])*math.sin(angle),-int(p[1])*math.sin(angle)+int(p[2])*math.cos(angle))
def toGameMatrix(points):
#	p1 = points[0]
#	p2 = points[1]
#	a = getLength(p1,p2)
#	if p1[2] > p2[2]:
#		p3 = (p1[0],p2[1],p1[2])
#		b = getLength(p1,p3)
#	else:
#		p3 = (p1[0],p1[1],p2[2])
#		b = getLength(p2,p3)
	#angle = math.asin(b/a)
#	angle = 0;
	rpoints = []
	for i in xrange(4):
#		rpoints.append(rotatePoint(points[i],angle))
		rpoints.append((int(points[i][1]),int(points[i][2])))
	print "minus point: ",rpoints[0]
	x = rpoints[0][0]
	y = rpoints[0][1]		
	for i in xrange(4):
		print "b: ",rpoints[i]
		rpoints[i] = (math.fabs(rpoints[i][0] - x),math.fabs(rpoints[i][1] - y))
		print "a: ",rpoints[i]
	return x,y,rpoints
def getMatrixPos(p,(x,y)):
#	rp = rotatePoint(p,angle)
	return (int(p[1]) - x,-(int(p[2]) - y))
	
#returns tuple (size,borderpoints)
def sortPoints(points):
	#psorted.append(p)
	sorted(points, key=lambda p: p[2])
	points.reverse();
	ftwo = points[0:2]
	stwo = points[2:4]
	sorted(ftwo, key=lambda p: p[1])
	sorted(stwo, key=lambda p: p[1])
	stwo.reverse();
	points[0] = ftwo[0]
	points[1] = ftwo[1]
	points[2] = stwo[0]
	points[3] = stwo[1]
	
def defineMatrix(a,b,c,d):
	p1 = getUTM(a)
	p2 = getUTM(b)
	p3 = getUTM(c)
	p4 = getUTM(d)
	if p1[0] != p2[0] or p2[0] != p3[0] or p3[0] != p4[0]:
		print "area is too big"
		return
	points = [p1,p2,p3,p4]
	#sortPoints(points)
	w = getLength(points[0],points[1])
	h = getLength(points[1],points[2])
	return ((w,h),(points))
def main():
	##enter microdegrees
#	(53433367, -2957253)
#(53426821, -2957253)
#(53433367, -2946953)
#(53426821, -2946953)
#Game Size is: (728, 684)
#127.0.0.1 Connected!
#Sending data back
#127.0.0.1 Connected!
#points-Before: (53430366, -29570530)
#points-After: (329228, -5923224)
	size,points = defineMatrix((53433367, -2957253),(53426821, -2957253),(53433367, -2946953),(53426821, -2946953))
	print size,points	
	x,y,borders = toGameMatrix(points) 
	print "border: ", borders
	point = getUTM((53432367, -2954253))
	print "x: ",x ," y: ",y
	print "point: ",point
	print getMatrixPos((point),(x,y))
if __name__ == '__main__':
    main()
